<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>82. 删除排序链表中的重复元素 II</title>
  </head>
  <body>
    <script>
      // 给定一个已排序的链表的头 head ， 删除原始链表中所有重复数字的节点，只留下不同的数字 。返回 已排序的链表 。
      //     输入：head = [1,2,3,3,4,4,5]
      // 输出：[1,2,5]

      /**
       * Definition for singly-linked list.
       */
      function ListNode(val, next) {
        this.val = val === undefined ? 0 : val
        this.next = next === undefined ? null : next
      }

      /**
       * @param {ListNode} head
       * @return {ListNode}
       */
      var deleteDuplicates = function (head) {
        // debugger
        // if (!head || !head.next) {
        //   return head
        // }
        // let num = head.val
        // let isCut = false
        // let nowNode = new ListNode(num - 1, head)
        // let preNowList = nowNode
        // head = nowNode
        // num = num - 1
        // let nextNode = head.next
        // while (nextNode) {
        //   if (nextNode.val === num) {
        //     isCut = true
        //   }
        //   if (nextNode.val !== num && !isCut) {
        //     preNowList = nowNode
        //     nowNode = nowNode.next
        //     num = nextNode.val
        //   }
        //   if (nextNode.val !== num && isCut) {
        //     preNowList.next = nextNode
        //     num = nextNode.val
        //     isCut = false
        //   }
        //   nextNode = nextNode.next
        // }
        // if (isCut) {
        //   preNowList.next = null
        // }
        // return head.next

        if (!head) {
          return head
        }

        const dummy = new ListNode(0, head)

        let cur = dummy
        while (cur.next && cur.next.next) {
          if (cur.next.val === cur.next.next.val) {
            const x = cur.next.val
            while (cur.next && cur.next.val === x) {
              cur.next = cur.next.next
            }
          } else {
            cur = cur.next
          }
        }
        return dummy.next
      }

      const b = new ListNode(0)
      const a = new ListNode(0, b)
      const end = new ListNode(-1, a)
      const next = new ListNode(-1, end)
      const head = new ListNode(-2, next)
      console.log(deleteDuplicates(head))
    </script>
  </body>
</html>
